from django.conf import settings
from django.contrib.auth import login
from django.http import JsonResponse,HttpResponseForbidden
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from QQLoginTool.QQtool import OAuthQQ

from apps.oauth.models import OAuthQQUser
from apps.users.models import User
from meiduo_mall.settings.dev import logger
from utils.response_code import RETCODE

def is_bind_openid(request,openid):
    try:
        oauth_user = OAuthQQUser.objects.get(openid=openid)
    except Exception as e:
        logger.error(e)

        from utils.seceret import SecretOauth
        secret_openid = SecretOauth().dumps({'openid':openid})

        context = {
            'openid':openid
        }
        return render(request,'oauth_callback.html',context)


    else:
        qq_user = oauth_user.user
        login(request, qq_user)

        response = redirect(reverse('contents:index'))

        # 登录时用户名写入到cookie，有效期15天
        response.set_cookie('username', qq_user.username, max_age=3600 * 24 * 15)

        return response

class QQAuthView(View):
    def get(self,request):
        code = request.GET.get('code')
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,client_secret=settings.QQ_CLIENT_SECRET,redirect_uri=settings.QQ_REDIRECT_URI,state='')
        token = oauth.get_access_token(code)
        openid = oauth.get_open_id(token)

        response = is_bind_openid(request,openid)
        return response

    def post(self, request):
        mobile = request.POST.get('mobile')
        pwd = request.POST.get('password')
        sms_code = request.POST.get('sms_code')
        openid = request.POST.get('openid')

        from utils.seceret import SecretOauth
        openid = SecretOauth().loads(openid).get('openid')

        if not openid:
            return render(request, 'oauth_callback.html', {'openid_errmsg': '无效的openid'})
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            user = User.objects.create(username=mobile,password=pwd,mobile=mobile)
        else:
            if not user.check_password(pwd):
                return render(request, 'oauth_callback.html', {'account_errmsg': '用户名或密码错误'})

        try:
            OAuthQQUser.objects.create(openid=openid,user=user)

        except Exception as e:
            return render(request, 'oauth_callback.html', {'qq_login_errmsg': 'QQ登录失败'})

        login(request,user)
        response = redirect(reverse('contents:index'))
        response.set_cookie('username',user.username,max_age=24 *15 * 3600)
        return response

class QQAuthURLView(View):
    def get(self,request):
        oauth = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state=''
        )
        login_url = oauth.get_qq_url()

        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'login_url':login_url})


